package project.ccso.top.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import project.ccso.top.bean.GridPageBean;
import project.ccso.top.bean.ReturnResult;
import project.ccso.top.entity.Member;
import project.ccso.top.enumerate.Result;
import project.ccso.top.service.MemberService;
import project.ccso.top.service.impl.MemberServiceImpl;

/**
 * MemberServlet
 * 处理与Member相关的请求
 * @author aibinxiao
 * @date 2018年8月23日 上午10:52:42
 */
@WebServlet("/MemberServlet")
public class MemberServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private static int cookieExpireTime = 120*24*60*60;
	private static final Logger logger = LoggerFactory.getLogger(MemberServlet.class);
	// 数据json格式转换
	private static ObjectMapper mapper = new ObjectMapper();
	private MemberService memberService = new MemberServiceImpl();
    
	/**
	 * 跳转到主页
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOExceptionS
	 */
    public void gotoIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("member/index.jsp").forward(request, response);
	}
	
    /**
     * 检查用户手机号是否已经注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
	public void isRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		String telphone = request.getParameter("telephone");
		ReturnResult result = new ReturnResult();
		boolean flag = false;
		try {
			flag = memberService.findByPhoneNumber(telphone);
			if(flag) {
				result.setResult(Result.SUCCESS.name());
				result.setMessage("该手机已经注册过了！");
				logger.info(result.getMessage());
			}else {
				result.setResult(Result.FAILED.name());
				result.setMessage("该手机还未注册！");
				logger.error(result.getMessage());
			}
			result.setData(flag);
		} catch (Exception e) {
			result.setResult(Result.FAILED.name());
			result.setMessage(e.getMessage());
			result.setData(flag);
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		writer.print(mapper.writeValueAsString(result));
	}
    
    /**
     * 用户注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
	public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		String telphone = request.getParameter("telphone");
		String password = request.getParameter("password");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String school = request.getParameter("school");
		ReturnResult result = new ReturnResult();
		boolean flag = false;
		try {
			flag = memberService.addMember(telphone, password, province, city, school);
			if(flag) {
				result.setResult(Result.SUCCESS.name());
				result.setMessage("恭喜您，注册成功！");
				logger.info(result.getMessage());
			}else {
				result.setResult(Result.FAILED.name());
				result.setMessage("对不起，注册失败！");
				logger.error(result.getMessage());
			}
			result.setData(flag);
		} catch (Exception e) {
			result.setResult(Result.FAILED.name());
			result.setMessage(e.getMessage());
			result.setData(flag);
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		writer.print(mapper.writeValueAsString(result));
	}
	
	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String rememberAcctount = request.getParameter("rememberAccount");
		ReturnResult result = new ReturnResult();
		Member existMember = null;
		try {
			existMember = memberService.login(account, password);
			result.setResult(Result.SUCCESS.name());
			result.setMessage("用户登录成功！");
			logger.info(result.getMessage());
		} catch (Exception e) {
			result.setResult(Result.FAILED.name());
			result.setMessage("用户登录失败！");
			e.printStackTrace();
			logger.error(result.getMessage());
		}
		
		// 判断
		if (existMember == null) {
			request.getRequestDispatcher("member/login.jsp").forward(request, response);
		} else {
			session.setAttribute("existUser", existMember);
			if(!StringUtils.isEmpty(rememberAcctount) && "on".equals(rememberAcctount)) {
				// 勾选了记住密码，写入到cookie
				Cookie cookie = new Cookie("userId", existMember.getId().toString());
                cookie.setMaxAge(cookieExpireTime);
                cookie.setPath("/");
                response.addCookie(cookie);
			}
			request.getRequestDispatcher("member/index.jsp").forward(request, response);
		}
	}
	
	/**
	 * 用户注销登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		HttpSession session = request.getSession();
		Member user = (Member) session.getAttribute("existUser");
		ReturnResult result = new ReturnResult();
		
		if (user != null) {
            logger.info("user logout: userId = " + user.getId());
            // 清除session
            session.removeAttribute("user");
            session.removeAttribute("userSessionBean");
            session.invalidate();
            // 清除cookie
            Cookie cookie = new Cookie("userId", user.getId().toString());
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
            result.setResult(Result.SUCCESS.name());
            result.setMessage("当前账号退出成功！");
            logger.info(result.getMessage());
        } else {
        	result.setMessage("当前Session中user为null！");
        	result.setResult(Result.FAILED.name());
            logger.error("当前Session中user为null！");
        }
		writer.print(mapper.writeValueAsString(result));
	}
	
	/**
	 * 新用户注册获取短信验证码
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getSmsCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		HttpSession session = request.getSession();
		String telphone = request.getParameter("telphone");
		ReturnResult result = new ReturnResult();
		// 获取短信验证码
		boolean flag = true;
		String smsCode = null;
		try {
			smsCode = memberService.getSmsCode(telphone);
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		if(flag && !StringUtils.isEmpty(smsCode)) {
			// 发送成功，没有出错
			result.setResult(Result.SUCCESS.name());
			result.setMessage("验证码发送成功！");
			logger.info(result.getMessage());
		}else {
			// 发生错误
			result.setResult(Result.FAILED.name());
			result.setMessage("验证码发送失败！");
			logger.error(result.getMessage());
		}
		result.setData(flag);
		session.setAttribute("smsCode", smsCode);
		writer.print(mapper.writeValueAsString(result));
	}
	
	/**
	 * 校验用户输入的短信验证码和产生的验证码是否一致
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void checkSmsCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		HttpSession session = request.getSession();
		String inputSmsCode = request.getParameter("inputSmsCode");
		ReturnResult result = new ReturnResult();
		String sessionSmsCode = (String) session.getAttribute("smsCode");
		boolean flag = true;
		
		try {
			flag = memberService.checkSmsCode(inputSmsCode, sessionSmsCode);
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		if(flag) {
			// 用户输入的短信验证码和产生的验证码一致
			result.setResult(Result.SUCCESS.name());
			result.setMessage("短信验证码正确！");
			logger.info(result.getMessage());
		}else {
			// 用户输入的短信验证码和产生的验证码不一致
			result.setResult(Result.FAILED.name());
			result.setMessage("短信验证码错误！");
			logger.error(result.getMessage());
		}
		result.setData(flag);
		writer.print(mapper.writeValueAsString(result));
	}

	/**
	 * 根据用户ID查询用户信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
    public void findUserMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                              
    	HttpSession session = request.getSession(); 
    	PrintWriter writer = response.getWriter();
    	//获取以登录的用户的session
		Member user = (Member) session.getAttribute("existUser");
		user = memberService.findById(user.getId());
		//将数据传递给jsp页面ajax
		writer.print(mapper.writeValueAsString(user));
		
	}
    
    /**
     * 根据用户Id修改用户信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void updateUserMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	System.out.println("程序到了updateUserMessage");
    	HttpSession session = request.getSession(); 
    	PrintWriter writer = response.getWriter();
    	//获取以登录的用户的session
		Member user = (Member) session.getAttribute("existUser");
	    Integer id = user.getId();
	    Member user2 = new Member();
    	String phoneNumber = request.getParameter("phoneNumber");
    	String nickName = request.getParameter("nickName");
    	int  sex = Integer.parseInt(request.getParameter("sex"));
    	String portrait = request.getParameter("portrait");
    	String province = request.getParameter("province");
    	System.out.println(province);
    	String city = request.getParameter("city");
    	System.out.println(city);
    	String school = request.getParameter("school");
    	System.out.println(school);
    	user2 = new Member(id,phoneNumber,nickName,sex,portrait,province,city,school);
    	Boolean boolReault = memberService.updateMessageById(user2);
    	System.out.println(id+phoneNumber+nickName+portrait+province+city+school);
    	writer.print(mapper.writeValueAsString(boolReault));
    }	
    
    
    /**
     * 根据用户Id修改用户密码
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void updateUserPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	System.out.println("程序到了updateUserPassword");
    	HttpSession session = request.getSession(); 
    	PrintWriter writer = response.getWriter();
    	//获取以登录的用户的session
		Member user = (Member) session.getAttribute("existUser");
		Integer id = user.getId();
		Member user2 = new Member();
		String newPassword = request.getParameter("newPassword");
		//将数据传递给jsp页面ajax
		user2 = new Member(id,newPassword);
    	Boolean boolReault = memberService.updatePasswordById(user2);
    	if("true".equals(boolReault)) {
    		System.out.println("修改成功");
    	}else {
    		System.out.println("修改失败");
    	}
		writer.print(mapper.writeValueAsString(boolReault));
    }
    
    /**
     * 分页查询用户信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		ReturnResult result = new ReturnResult();
		String pageNo = request.getParameter("page"); // pageNum 页码
		String pageSize = request.getParameter("rows"); // pageSize 每页条数
		String id = request.getParameter("id");
		String nickName = request.getParameter("nickName");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		GridPageBean<Member> pageBean = null;
		try {
			pageBean = memberService.findByPage(pageNo, pageSize, id, nickName, startDate, endDate);
			result.setResult(Result.SUCCESS.name());
			result.setMessage("查询第" + pageNo + "页的用户信息成功！");
			logger.info(result.getMessage());
		} catch (Exception e) {
			result.setResult(Result.FAILED.name());
			result.setMessage(e.getMessage());
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		result.setData(pageBean);
		writer.print(mapper.writeValueAsString(result));
	}
    
    /**
     * 用户屏蔽或启用
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void updateShieldStatus(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		ReturnResult result = new ReturnResult();
		String id = request.getParameter("id");
		String statusStr = request.getParameter("status");
		boolean flag = false;
		try {
			flag = memberService.updateShieldStatus(id, statusStr);
			result.setResult(Result.SUCCESS.name());
			if("0".equals(statusStr)) {
				result.setMessage("id为" + id + "的用户启用成功！");
			}else if("1".equals(statusStr)) {
				result.setMessage("id为" + id + "的用户屏蔽成功！");
			}
			logger.info(result.getMessage());
		} catch (Exception e) {
			result.setResult(Result.FAILED.name());
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		result.setData(flag);
		writer.print(mapper.writeValueAsString(result));
	}
    
}
